package com.example.ktapplication.model
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.elvishew.xlog.XLog
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.bean.CollectBean
import com.example.ktapplication.bean.HomeBannerBean
import com.example.ktapplication.state.HomeBannerState
import com.example.ktapplication.utils.NetworkUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import com.example.ktapplication.net.NetRepository
import com.example.ktapplication.state.CollectState

class CollectViewModel : ViewModel() {

    private val _state = MutableStateFlow<CollectState>(CollectState.OnSuccess(null))
    val state: StateFlow<CollectState> = _state

    var page:Int=0

    fun getHomeBannerData(page:Int) {
        this.page=page
        viewModelScope.launch {
            collect.flowOn(Dispatchers.IO)
                .catch { exception ->
                    _state.value = CollectState.OnError(exception)
                }
                .collect { data ->
                    _state.value = CollectState.OnSuccess(data)
                }
        }
    }

    private val collect: Flow<CollectBean> = flow {
        if (!NetworkUtils.isConnected(AppGlobals.getApplication())){
            throw RuntimeException("网络未连接")
        }
        //网络请求
        val collect =  NetRepository.instance.service.getCollectionArticles(page)
        //返回结果
        emit(collect)
    }

    override fun onCleared() {
        super.onCleared()
    }
}